import { Bmobs } from "../plugins/bmob";

class UserDao extends Bmobs {
  constructor() {
    super()
  }
  /**
   * 获取所有用户信息
   */
  public getAllUser():Object {
    return this.QueryAll();
  }

  public getOne(objectId: string):Object {
    return this.QueryOne(objectId);
  }

  /**
   * 发送短信验证码
   * @param params
   * {
   *   userphone: 手机号
   * }
   * @constructor
   */
  public async sendSmsCode (params: object): Promise<Object> {
    return new Promise((resolve, reject) => {
      this.BmobObject.requestSmsCode({
        "mobilePhoneNumber": params['userphone'],
        "template": "guaike"
      }).then(function (res) {
        resolve(res);
      }).catch(function (err) {
        resolve(err);
        });
    });
  }

  /**
   * 手机号码和验证码一键快速登录的功能
   * @param params
   */
  public async loginSms (params: object): Promise<Object> {
    return new Promise((resolve, reject) => {
      this.BmobObject.verifySmsCode(params['smscode'], {
        mobilePhoneNumber: params['userphone']
      }).then((response) => {
        if(response.hasOwnProperty("msg")) {

          this.query.equalTo("phone","==",params['userphone'])
          this.query.find().then(res => {
            resolve(res);
          }).catch(function (error) {
            resolve(error);
          });

        } else {
          resolve(response);
        }

      }).catch(function (error) {
        resolve(error);
        });
    })
  }


  public async userRegister (params: Object): Promise<Object> {
    return new Promise((resolve, reject) => {
      this.BmobObject.User.register({
        username: params['username'],
        password: params['userpassword'],
        email: params['useremail'],
        phone: params['userphone']
      }).then(res => {
        resolve(res)
      }).catch(err => {
        resolve(err)
      });
    })
  }

}

export default new UserDao();
